package com.zimmur.tools;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 访问身份验证
 * @author Administrator
 *
 */
public final class RequestAuthorVerify {
	private static Logger log = LoggerFactory.getLogger(RequestAuthorVerify.class);
	
	private final static String Charset = "utf-8";
	/**
	 * 访问身份验证
	 * @param request 请求方法(GET/POST)
	 * @param sign 请求签名
	 * @param token 用户授权码
	 * @param key  公钥
	 * @return true = 验证通过 false=验证失败
	 */
	public static boolean checkAuthor(HttpServletRequest request,String sign,String token,String key){
		boolean bRet = false;
		try {
			String timestamp = request.getHeader("timestamp");
			//加密方法: httpMethod + apiUri + timestamp + token+ body数据长度
			String uri = request.getRequestURI();
			String method = request.getMethod();
			//计算参数长度
			String bodyLength=request.getHeader("body_length");
			
			String content = method+uri+timestamp+token+key+bodyLength;
			//"GET"+uri+timeunix+token+key+"0";
			String md5 = MD5Util.MD5Encode(content, Charset).toUpperCase();
			if(md5.equals(sign)){
				return true;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return bRet;
	}
	public static String checkAuthorTest(HttpServletRequest request,String sign,String token,String key){
		String content="";
		try {
			String timestamp = request.getHeader("timestamp");
			//加密方法: httpMethod + apiUri + timestamp + token+ body数据长度
			String uri = request.getRequestURI();
			String method = request.getMethod();
			//计算参数长度
			String bodyLength=request.getHeader("body_length");
			
			content = method+uri+timestamp+token+key+bodyLength;
			//"GET"+uri+timeunix+token+key+"0";
			String md5 = MD5Util.MD5Encode(content, Charset).toUpperCase();
			if(md5.equals(sign)){
				return null;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return content;
	}
}
